import { _decorator, Component, dragonBones } from "cc";
import { app } from "db://app-game/core/app";
import { DBRoleType } from "../../../common/db/db-role/DBRole.type";
import { Role } from "../Role";
import { GameEvent } from "../../../common/config/GameEvent";

const { ccclass, property } = _decorator;

/** 角色资源加载 */
@ccclass("RoleViewLoader")
export class RoleViewLoader extends Component {
  role: Role = null!;
  /* 角色上半身 */
  upperBody: dragonBones.ArmatureDisplay = null!;
  /** 角色下半身 */
  lowerBody: dragonBones.ArmatureDisplay = null!;

  protected onLoad(): void {
    this.node.on("load", this.onEmitLoad, this);
  }

  private async onEmitLoad(role: Role) {
    this.role = role;
    this.upperBody = role.RoleView!.upperBody;
    this.lowerBody = role.RoleView!.lowerBody;
    let anim = role.RoleModel.data.anim;
    await this.load(anim);
  }

  private async load(anim: DBRoleType["anim"]) {
    this.node.active = false;
    await this.loadDragonDones(anim);
    // app.res.load(
    //   anim.upperBody.asset,
    //   dragonBones.DragonBonesAsset,
    //   (err: Error | null, db: dragonBones.DragonBonesAsset) => {
    //     this.dragonBones.dragonAsset = db;
    //     app.res.load(
    //       anim.upperBody.atlasAsset,
    //       dragonBones.DragonBonesAtlasAsset,
    //       (err: Error | null, atlas: dragonBones.DragonBonesAtlasAsset) => {
    //         this.dragonBones.dragonAtlasAsset = atlas;
    //         this.dragonBones.armatureName = "indiv";
    //         this.dragonBones.enabled = true;
    //         this.dragonBones.playAnimation("attacks", 0);
    //         this.node.active = true;
    //       }
    //     );
    //   }
    // );
  }

  /** 加载龙骨 */
  private async loadDragonDones(anim: DBRoleType["anim"]) {
    try {
      const dragonData = await Promise.all([
        app.res.loadAsync(anim.upperBody.asset, dragonBones.DragonBonesAsset),
        app.res.loadAsync(
          anim.upperBody.atlasAsset,
          dragonBones.DragonBonesAtlasAsset
        ),
        app.res.loadAsync(anim.lowerBody.asset, dragonBones.DragonBonesAsset),
        app.res.loadAsync(
          anim.lowerBody.atlasAsset,
          dragonBones.DragonBonesAtlasAsset
        ),
      ]);
      // 1.上半身龙骨赋值
      this.upperBody.dragonAsset = dragonData[0];
      this.upperBody.dragonAtlasAsset = dragonData[1];
      this.upperBody.armatureName = anim.upperBody.armatureName;
      this.upperBody.enabled = true;
      this.node.active = true;

      // 2.下半身龙骨赋值
      this.lowerBody.dragonAsset = dragonData[2];
      this.lowerBody.dragonAtlasAsset = dragonData[3];
      this.lowerBody.armatureName = anim.lowerBody.armatureName;
      this.lowerBody.enabled = true;
      this.node.active = true;

      // 3.通知切换武器
      this.role.switchWeapon({
        lowerBody: anim.lowerBody.armatureName,
        upperBody: anim.upperBody.armatureName,
      });
    } catch (error) {
      console.log(error, "加载骨骼失败", anim);
    }
  }
}
